//
//  TopTabBar.m
//  book
//
//  Created by liwei on 15/6/17.
//  Copyright (c) 2015年 liwei. All rights reserved.
//

#import "TopTabBar.h"

@interface TopTabBar () {
    UIView *accessView;
    NSMutableArray *buttons;
}

@end

@implementation TopTabBar

- (void)updateLayout {
    
    buttons = [NSMutableArray array];
    
    float width = self.frame.size.width / self.titleList.count;
    float height = self.frame.size.height;
    for (int i = 0; i < self.titleList.count; i++) {
        
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(i * width, 0, width, height)];
        [btn setTitle:self.titleList[i] forState:UIControlStateNormal];
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:16];
        [btn addTarget:self action:@selector(btn_click:event:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = i;
        [self addSubview:btn];
        
        if (i != 0) {
            UIView *l = [[UIView alloc] initWithFrame:CGRectMake(i * width, 8, 1, height - 16)];
            l.backgroundColor = HexRGB(0xE4E5E6);
            [self addSubview:l];
        }
        
        [buttons addObject:btn];
        
    }
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, height - 1, self.frame.size.width, 1)];
    line.backgroundColor = HexRGB(0xE4E5E6);
    [self addSubview:line];
    
    accessView = [[UIView alloc] initWithFrame:CGRectMake(0, height - 2, width, 2)];
    accessView.backgroundColor = GET_HEX_COLOR(NAVBAR_BG_COLOR);
    [self addSubview:accessView];
    
}

- (void) btn_click: (UIButton *) sender event: (id) event {
    [self setIndex:(int)sender.tag];
}

- (void)setIndex:(int)index {
    [buttons[_index] setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    _index = index;
    [buttons[_index] setTitleColor:GET_HEX_COLOR(NAVBAR_BG_COLOR) forState:UIControlStateNormal];
    float width = self.frame.size.width / self.titleList.count;
    CGRect accessViewFrame = accessView.frame;
    accessViewFrame.origin.x = width * index;
    [UIView animateWithDuration:0.3 animations:^{
        accessView.frame = accessViewFrame;
    }];
    
    if (self.delegate) {
        [self.delegate selectAtIndex:index inTabBar:self];
    }
}

@end
